package com.tacc.tyun.util;

import com.tacc.tyun.controller.FileController;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
* 文件上传
*
* @author congcong tao
* @date 2017/9/4 16:53
*/
public class FileUploadUtil {

    private static Logger LOGGER= LoggerFactory.getLogger(FileController.class);

    private final static ProProperties proProperties = (ProProperties) SpringContextUtils.getBean("proProperties");

    public List<String> uplodCompress(MultipartFile[] myfiles) throws IOException {

        List<String> urlList=new ArrayList<>();
        for(MultipartFile myfile : myfiles){
            String newFileName = null;
            String sizeFileName = null;
            if(myfile.isEmpty()){
                LOGGER.info("请选择文件后上传");
                return null;
            }else{
                //newFileName = DateUtil.DateToStr(new Date(),DateUtil.DATE_TIME_PATTERN_1)+ BaseUtil.acceptRandom(BaseUtil.NUMBER_CONTENT,6)+"."+BaseUtil.acceptFileType(myfile.getOriginalFilename());
                newFileName= FilePathUtil.getFilePath(myfile.getOriginalFilename());
                LOGGER.info("文件名: " + newFileName+";文件原名: " + myfile.getOriginalFilename()+";文件名称: " + myfile.getName()+";文件长度: " + myfile.getSize()+";文件类型: " + myfile.getContentType());
                try {
                    File targetFile = new File(newFileName);
                    FileUtils.copyInputStreamToFile(myfile.getInputStream(),targetFile);
                    //此时targetFile应该就是file流
                    sizeFileName = ImangeUtil.createNewImage(targetFile, 2, 360, 200);//等比例压缩
                    // 生成图片的绝对引用地址
                    String picUrl = StringUtils.replace(StringUtils.substringAfter(sizeFileName, proProperties.getBaseUploadURL()),"\\", "/");
                    String baseVisitURL=proProperties.getBaseVisitURL()+picUrl;
                    urlList.add(baseVisitURL);

                } catch (Exception e) {
                    LOGGER.info("文件[" + newFileName + "]上传失败,堆栈轨迹如下");
                    e.printStackTrace();
                    return null;
                }
            }
        }
        return urlList;
    }

}
